package net.huashitong.supervision.task.controller;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDeptRoom;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.sys.service.SysDeptRoomService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import javafx.scene.shape.Cylinder;
import net.huashitong.supervision.excel.Entity.ExcelDataEntity;
import net.huashitong.supervision.excel.service.ExcelDataService;
import net.huashitong.supervision.insideDuCha.entity.InsideCycleEntity;
import net.huashitong.supervision.insideDuCha.entity.InsideMainTaskEntity;
import net.huashitong.supervision.insideDuCha.entity.InsideSubTaskEntity;
import net.huashitong.supervision.insideDuCha.entity.InsideUserTaskEntity;
import net.huashitong.supervision.insideDuCha.filter.InsideMainTaskFilter;
import net.huashitong.supervision.insideDuCha.filter.InsideSubTaskFilter;
import net.huashitong.supervision.insideDuCha.filter.InsideUserTaskFilter;
import net.huashitong.supervision.insideDuCha.service.InsideCycleService;
import net.huashitong.supervision.insideDuCha.service.InsideMainTaskService;
import net.huashitong.supervision.insideDuCha.service.InsideSubTaskService;
import net.huashitong.supervision.insideDuCha.service.InsideUserTaskService;
import net.huashitong.supervision.task.dataBean.TaskBackNewBean;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.EvalRulesFilter;
import net.huashitong.supervision.task.filter.TaskMainFilter;
import net.huashitong.supervision.task.service.*;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static net.huashitong.supervision.task.controller.TaskUnitController.splitString;

/**
 * 单位内部督查功能，
 * 任务派发给到人员，而不是派发到单位，
 * 由相应的人员反馈
 */
@Controller
@RequestMapping(value = "/insideDept")
public class InsideDeptCtrl extends JsonBaseController {

    @Autowired
    private InsideMainTaskService mainTaskService;
    @Autowired
    private InsideSubTaskService insideSubTaskService;
    @Autowired
    private InsideUserTaskService insideUserTaskService;

    @Autowired
    private TaskBackNewService taskBackNewService;
    @Autowired
    private SysDeptRoomService deptRoomService;

    @Autowired
    private TaskLogNewService tasklogService;
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private InsideCycleService cycleService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ExcelDataService excelDataService;
    @Autowired
    private RoomUserService roomUserService;

    @Override
    protected String getView(String s) {
        return "/modules/task/insideDept/" + s;
    }

    /**
     * 获取立项人的单位 ，以及同单位下的人
     */
    @ResponseBody
    @RequestMapping(value = "/getDeptUsers", method = RequestMethod.GET)
    public List<SysUserDataBean> getDeptUsers(InsideMainTaskFilter filter) {
        return getDeptUsersMode();
    }

    public List<SysUserDataBean> getDeptUsersMode() {
        String deptId = SysUserUtils.getDeptId();
        String roleId = SysUserUtils.getRoleId(); // 02 主要领导； 03分管领导 04 经办
        List<SysUserDataBean> dataList = new ArrayList<>();
        List<SysUserDataBean> dataList1 = new ArrayList<>();



        String userId = SysUserUtils.getUserId();// 当前登录这的Id
        if (null == userId || "".equals(userId)) {
            return dataList;
        }

        SysUserDataBean bean = new SysUserDataBean();
        bean.setUserId("");
        bean.setName("全选");
        dataList.add(0,bean);

        List<SysUserDataBean> sysUserDataBeans = loginService.getByDeptId(deptId);
      /*  Map<String, String> userMap = sysUserDataBeans.stream().collect(Collectors.toMap(SysUserDataBean::getUserId, SysUserDataBean::getName));

        if ("03".equals(roleId)||"02".equals(roleId)) {
            List<SysUserDataBean> houXuanList = new ArrayList<>();
            //取出 分管的科室
            List<SysDeptRoom> byLeader = deptRoomService.getByLeader(SysUserUtils.getUserId());
//            for (SysDeptRoom sysDeptRoom : byLeader) {
//                List<SysUserDataBean> collect = sysUserDataBeans.stream().filter(o -> sysDeptRoom.getSysId().equals(o.getRoomId())).collect(Collectors.toList());
//                sysUserDataBeans.stream().filter(o -> sysDeptRoom.getSysId().equals(o.getRoomId())).collect(Collectors.toList());
//                dataList1.addAll(collect);
//            }
            //将 科室加工成选项
            int index =1;
            for (SysDeptRoom itemRoom : byLeader) {//取出这个科室下的所有人id
                List<RoomUserEntity> listUsers = roomUserService.getUsersByRoomId(itemRoom.getRoomId());
                String userIds = "";
                for (RoomUserEntity item : listUsers) {
                    userIds=item.getUserId()+",";
                    //设置候选人
                    SysUserDataBean bean2 = new SysUserDataBean();
                    bean2.setUserId(item.getUserId());
                    bean2.setName(userMap.get(item.getUserId()));
                    houXuanList.add(bean2);
                }
                SysUserDataBean bean1 = new SysUserDataBean();
                bean1.setUserId(userIds);
                bean1.setName(itemRoom.getRoomName());
                dataList.add(index,bean1);
                index=index+1;
            }
            //根据userId 去重
            houXuanList = houXuanList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                    new TreeSet<>(Comparator.comparing(n->n.getUserId()))), ArrayList::new));

            dataList1=houXuanList;

        } else {
//        过滤公共账号
            dataList1 = sysUserDataBeans.stream().filter(sysUserDataBean -> (!"1".equals(sysUserDataBean.getPersonSignal()))).collect(Collectors.toList());
        }*/
        //过滤自己
        dataList1 = sysUserDataBeans.stream().filter(o -> !o.getUserId().equals(userId)).collect(Collectors.toList());

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < dataList1.size(); i++) {
            if (i != 0) {
                sb.append("," + dataList1.get(i).getUserId());
            }else{
                sb.append(dataList1.get(i).getUserId());
            }
        }

        //新增一个全选
        SysUserDataBean sysUserDataBean = dataList.get(0);
        sysUserDataBean.setUserId(sb.toString());
        dataList.remove(0);
        dataList.add(0,sysUserDataBean);

        dataList.addAll(dataList1);//
        return dataList;
    }


    /**
     * 内部立项页面
     *
     * @return
     */
    @RequestMapping(value = "/setup")
    public String allTask(Model model) {

        model.addAttribute("deptId", SysUserUtils.getDeptId());
        return getView("/nbLiXiang");
    }

    /**
     * 内部立项保存
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/setup", method = RequestMethod.POST)
    public Message allTask(InsideMainTaskFilter filter) {

        //List<InsideMainTaskEntity> query = mainTaskService.query();
        String deptId = SysUserUtils.getDeptId();
        if ("".equals(deptId) || null == deptId) {
            return coverMessage("500", "登陆过期");
        }

        if (null == filter.getTaskName()) {
            return coverMessage("500", "主任务名不能为空");
        }
        if (filter.getTimeType() == 1 && null == filter.getTimeLimit()) {
            return coverMessage("500", "单时限不能为空");
        } else if (2 == filter.getTimeType()) {
            switch (filter.getPeriod()) {
                case "0":
                    if (null == filter.getDay())
                        return coverMessage("500", "周期性时限不能为空");
                    break;
                case "2":
                    if (null == filter.getMonth() || "".equals(filter.getMonth()))
                        return coverMessage("500", "周期性时限不能为空");
                    break;
                case "3":
                    if (null == filter.getQuarter() || "".equals(filter.getQuarter()))
                        return coverMessage("500", "周期性时限不能为空");
                    break;
            }
        } else if (3 == filter.getTimeType()) {
            if (null == filter.getTimeLimits() || "".equals(filter.getTimeLimits())) {
                return coverMessage("500", "周期性时限不能为空");
            }
        }

        /*
              缓存获取批次号
         */
        List<InsideSubTaskFilter> insideSubTasks = null;
        String loginUserId = SysUserUtils.getUserId();
        String batchNum = redisService.get("insideBatch:" + loginUserId);
        if (ObjectUtils.isNotBlank(batchNum)) {
            List<ExcelDataEntity> listExcels = excelDataService.getByBatchNum(batchNum);
            listExcels = listExcels.stream().filter(entity -> entity.getFlags() == 1).collect(Collectors.toList());
            insideSubTasks = excelDataService.excelToInsideEntity(listExcels);
            filter.setInsideSubTasks(insideSubTasks);
        } else {

            insideSubTasks = filter.getInsideSubTasks();
        }


        int t = 1;
        for (InsideSubTaskFilter insideSubTask : insideSubTasks) {
            if (null == insideSubTask.getUserId() || "".equals(insideSubTask.getUserId())) {
                return coverMessage("500", "第" + t + "子事项承办人不能为空");
            }

            if (StringUtils.isBlank(insideSubTask.getSubTaskName())) {
                insideSubTask.setSubTaskName(filter.getTaskName());
                //return  coverMessage("500","第"+t+"子事项名不能为空");
            }
            if (insideSubTask.getTimeType() == 1 && null == insideSubTask.getSubTaskName()) {
                return coverMessage("500", "第" + t + "子事项单时限不能为空");
            } else if (2 == insideSubTask.getTimeType()) {
                switch (insideSubTask.getPeriod()) {
                    case "0":
                        if (null == insideSubTask.getDay())
                            return coverMessage("500", "第" + t + "子事项周期性时限不能为空");
                        break;
                    case "2":
                        if (null == insideSubTask.getMonth() || "".equals(insideSubTask.getMonth()))
                            return coverMessage("500", "第" + t + "子事项周期性时限不能为空");
                        break;
                    case "3":
                        if (null == insideSubTask.getQuarter() || "".equals(insideSubTask.getQuarter()))
                            return coverMessage("500", "第" + t + "子事项周期性时限不能为空");
                        break;
                }
            } else if (3 == insideSubTask.getTimeType()) {
                if (null == insideSubTask.getTimeLimits() || "".equals(insideSubTask.getTimeLimits())) {
                    return coverMessage("500", "第" + t + "子事项周期性时限不能为空");
                }
            }
            t = t + 1;
        }

        filter.setDeptId(deptId);
        List<InsideSubTaskFilter> listSubs = mainTaskService.saveTask(filter);
      /*  InsideMainTaskEntity entity = mainTaskService.saveMainTask(filter);
        if(null==entity){
            return coverMessage("500", "周期性参数错误");
        }
        //保存主任务

        //保存子任务
        List<InsideSubTaskFilter> listSubs = insideSubTaskService.saveSubTasks(entity, insideSubTasks);
        //保存人员的任务
        List<InsideSubTaskFilter> userTaskLists = insideUserTaskService.saveUsetTasks(listSubs);*/

        //保存到 定时任务提醒表；
        if (1 != filter.getTimeType()) {
            cycleService.saveUserCycleRemind(listSubs);
        }

        return coverMessage("200", "内部立项成功");
    }


    /**
     * 查看 所有内部任务
     */
    @RequestMapping(value = "/allinside", method = RequestMethod.GET)
    public String showAllTasks() {
        return getView("/allQuery");
    }

    /**
     * 初始化所有 主任务的数据
     */
    @ResponseBody
    @RequestMapping(value = "/allinside", method = RequestMethod.POST)
    public JqGrid initAllTasks(@ModelAttribute InsideMainTaskFilter filter) {

        String deptId = SysUserUtils.getDeptId();
        String roleId = SysUserUtils.getRoleId();//02 公共账号；
        if ("" == deptId || null == deptId) {
            return coverJqGrid(filter, null);
        }

        InsideMainTaskFilter mainFilter = new InsideMainTaskFilter();
        mainFilter.setDeptId(deptId);
        List<InsideMainTaskEntity> query = mainTaskService.getListMainTasks(mainFilter);
        return coverJqGrid(filter, query);
    }

    /**
     * 打开主任务详情 和底下的子任务数据
     */

    @RequestMapping(value = "/itemTasks/{id}", method = RequestMethod.GET)
    public String query2(Model model, @PathVariable String id) {
        //主任务id ; 获取子任务 以及相关人员
        System.out.println("id" + id);

        InsideMainTaskEntity mainTask = mainTaskService.getById(id);

        model.addAttribute("taskMain", mainTask);
        model.addAttribute("taskMainId", mainTask.getSysId());
        String loginId = SysUserUtils.getUserId();

        List<InsideUserTaskEntity> list = insideUserTaskService.getUserTaskByMainId(id);
        //判断是是否是承办人打开的本条任务，是的话，标记为 办理中
        List<InsideUserTaskEntity> collect = list.stream().filter(o -> o.getUserId().equals(loginId)).collect(Collectors.toList());
        if ("0".equals(mainTask.getTaskState()) && ObjectUtils.isNotBlank(collect)) {
            mainTask.setTaskState("1");
        }

        mainTaskService.update(mainTask);
        return getView("itemTasks");
    }

    /**
     * 初始化子任务表格数据
     */
    @ResponseBody
    @RequestMapping(value = "/itemTaskLists", method = RequestMethod.POST)
    public JqGrid getItemTasks(@ModelAttribute InsideSubTaskFilter filter) {
//taskMainId
        String roleId = SysUserUtils.getRoleId();
        List<InsideSubTaskEntity> listByMainId = insideSubTaskService.getListByMainId(filter.getTaskMainId(), roleId);

        return coverJqGrid(filter, listByMainId);
    }


    /**
     * 承办人打开子任务
     */
    @RequestMapping(value = "/backView/{id}", method = RequestMethod.GET)
    public String showChengBan(Model model, @PathVariable String id) {

        //id userTaskId  人员任务Id
        InsideUserTaskEntity userTask = insideUserTaskService.getById(id);
        model.addAttribute("taskUser", userTask);
        InsideSubTaskEntity subTask = insideSubTaskService.getById(userTask.getSubTaskId());

        InsideMainTaskEntity mainTask = mainTaskService.getById(subTask.getTaskMainId());

        InsideUserTaskFilter userTaskFilter = new InsideUserTaskFilter();
        userTaskFilter.setMainTaskId(subTask.getTaskMainId());
        userTaskFilter.setSubTaskId(subTask.getSysId());
      /*  List<InsideUserTaskFilter> userlist = insideUserTaskService.getUserlist(userTaskFilter);
        InsideUserTaskFilter userTask = userlist.get(0);
*/
        //
        subTask.setUserId(userTask.getUserId());
        SysLogin useInfo = loginService.getById(userTask.getUserId());
        subTask.setUserName(useInfo.getUsername());

        String userId = userTask.getUserId();//承办人的id
        String loginId = SysUserUtils.getUserId();//当前登陆者的id


        List<TaskBackNewBean> taskBackNewBeanList = new ArrayList<>();

        List<TaskBackNew> byTaskUnitId = taskBackNewService.getByTaskUnitId(userTask.getSysId());
        for (TaskBackNew taskBackNew : byTaskUnitId) {
            TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
            BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
            //反馈人名称
            taskBackNewBean.setSenderName(taskBackNew.getUserName());

//            taskBackNewBean.setFiles(taskBackNew.getFileName());

            String[] file = splitString(taskBackNew.getFile());
            String[] fileName = splitString(taskBackNew.getFileName());
            List<Map<String, Object>> backFileList = new ArrayList<>();
            if (ObjectUtils.isNotBlank(file)) {

                for (int i = 0; i < file.length; i++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("file", file[i]);
                    map.put("fileName", fileName[i]);
                    backFileList.add(map);
                }
            }
            taskBackNewBean.setFiles(backFileList);
            taskBackNewBeanList.add(taskBackNewBean);
        }

        if (userId.equals(loginId)) {//打开反馈页面
            // 页面打开完毕后，更新人员任务 反馈标志， backType  /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
            if ("0".equals(userTask.getTaskState())) { //代签收代为待反馈。 已经反馈过的页面，打开不改变状态
                userTask.setTaskState("1");
                insideUserTaskService.update(userTask);
            }
            model.addAttribute("taskBackNewList", taskBackNewBeanList);

            model.addAttribute("taskMain", mainTask);
            model.addAttribute("taskSub", subTask);

            return getView("backView");
        }


        /**
         * lixiang ren de yemian
         */
        List<TaskLogNew> byUnitId = tasklogService.getByUnitId(userTask.getSysId());
        // 页面打开完毕后，更新人员任务 反馈标志， backType  /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
        // userTask.setBackType("1");
        //insideUserTaskService.update(userTask);

        model.addAttribute("subTask", subTask);
        model.addAttribute("oldTask", null);
        //抄送领导给当前单位的批示信息
        model.addAttribute("leaderMessages", null);
        //单位任务实体类
        model.addAttribute("taskUnit", userTask);
        model.addAttribute("taskBackNewList", taskBackNewBeanList);
        model.addAttribute("taskSubName", subTask.getSubTaskName());
        model.addAttribute("taskSub", subTask);
        model.addAttribute("mainName", mainTask.getTaskName());
        model.addAttribute("logNewList", byUnitId);
        return getView("banjieView");
    }

    /**
     * 任务反馈
     */
    @ResponseBody
    @RequestMapping(value = "/backTasks", method = RequestMethod.POST)
    public Message chengBanDeital(InsideSubTaskFilter filter) {

        TaskBackNew taskBackNew = mainTaskService.saveFreebackTasks(filter);
        return coverMessage("200", "任务反馈成功");
    }

    /**
     * 办结任务
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/banJieTask", method = RequestMethod.POST)
    public Message banjieTask(InsideSubTaskFilter filter) {
        //子任务Id
        String banjieValue = filter.getBanjieValue();
        String userTaskId = filter.getSysId();
        InsideUserTaskEntity userTask = insideUserTaskService.getById(userTaskId);

        InsideSubTaskEntity byId = insideSubTaskService.getById(userTask.getSubTaskId());
        String taskMainId = null;
        List<InsideUserTaskEntity> ListuserTask = null;
        List<InsideSubTaskEntity> listSubs = null;
        InsideMainTaskEntity mainTask = null;
        switch (banjieValue) {
            case "1"://办结
                //状态（0未处理，1已批转，2反馈，3退回，4完成 .5已签收）
                byId.setTaskState("4"); // 4 已完成
                byId.setBackType("0");
                insideSubTaskService.update(byId);
                userTask.setTaskState(4 + "");
                insideUserTaskService.update(userTask);

                break;
            case "2": //完成
                taskMainId = byId.getTaskMainId();
                mainTask = mainTaskService.getById(taskMainId);
                mainTask.setTaskState("4");
                mainTask.setBackType("0");
                mainTaskService.update(mainTask);
                listSubs = insideSubTaskService.getByMainIdNoUserTask(taskMainId);
                listSubs.forEach(insideSubTaskEntity -> insideSubTaskEntity.setTaskState("4"));
                listSubs.forEach(insideSubTaskEntity -> insideSubTaskEntity.setBackType("0"));

                insideSubTaskService.batchUpdate(listSubs);
                ListuserTask = insideUserTaskService.getUserTaskByMainId(byId.getTaskMainId());
                ListuserTask.forEach(insideUserTaskEntity -> insideUserTaskEntity.setTaskState("4"));
                insideUserTaskService.batchUpdate(ListuserTask);
                break;
            case "3"://终止本周期性
                byId.setTaskState("4"); // 4 已完成
                byId.setBackType("0");
                insideSubTaskService.update(byId);
                userTask.setTaskState(4 + "");
                insideUserTaskService.update(userTask);
                //  List<InsideCycleEntity> insideCycleEntities = cycleService.queryFilterCycle(userTaskId, null, null, userTask.getUserId());
                List<InsideCycleEntity> insideCycleEntities = cycleService.queryFilterCycle(null, byId.getSysId(), null, null);
                if (ObjectUtils.isNotBlank(insideCycleEntities)) {

                    for (InsideCycleEntity item : insideCycleEntities) {
                        item.setValids("0");
                    }
                    cycleService.batchUpdate(insideCycleEntities);
                }

                break;
            case "4":
                taskMainId = byId.getTaskMainId();
                mainTask = mainTaskService.getById(taskMainId);
                mainTask.setBackType("0");
                mainTask.setTaskState("4");
                mainTaskService.update(mainTask);
                listSubs = insideSubTaskService.getByMainIdNoUserTask(taskMainId);
                listSubs.forEach(insideSubTaskEntity -> insideSubTaskEntity.setTaskState("4"));
                listSubs.forEach(insideSubTaskEntity -> insideSubTaskEntity.setBackType("0"));

                insideSubTaskService.batchUpdate(listSubs);
                ListuserTask = insideUserTaskService.getUserTaskByMainId(byId.getTaskMainId());
                ListuserTask.forEach(insideUserTaskEntity -> insideUserTaskEntity.setTaskState("4"));
                insideUserTaskService.batchUpdate(ListuserTask);
                List<InsideCycleEntity> cyclists = cycleService.queryFilterCycle(null, null, mainTask.getSysId(), null);
                if (ObjectUtils.isNotBlank(cyclists)) {
                    cyclists.forEach(o -> o.setValids(0 + ""));
                    cycleService.batchUpdate(cyclists);
                }
                break;
            default:
                return coverMessage("500", "操作失败");


        }


        return coverMessage("200", "操作成功");
    }


}
